package cn.com.lyj6851.common.validate.sms;

import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import cn.com.lyj6851.common.properties.RootSecurityProperties;
import cn.com.lyj6851.common.validate.code.ValidateCode;
import cn.com.lyj6851.common.validate.code.ValidateCodeGenerator;

/**
 * 短信验证码生成器
 */
@Component
public class SmsValidateCodeGenerator implements ValidateCodeGenerator {

    @Autowired
    private RootSecurityProperties securityProperties;

    @Override
    public ValidateCode generate(ServletWebRequest request) {
        //String code = RandomStringUtils.randomNumeric(securityProperties.getValidateCode().getSmsCode().getLength());
        String code = getRandomString(securityProperties.getValidateCode().getSmsCode().getLength());
    	return new ValidateCode(code, securityProperties.getValidateCode().getSmsCode().getExpireIn());
    }

    /**
     * 获取随机验证码
     * @param length 验证码的长度
     * @return
     */
    public static String getRandomString(int length) {
        String randomStr = "abcdefghijklmnopqrstuvwxyz0123456789";   
        Random random = new Random();   
        StringBuffer strBuf = new StringBuffer();   
        for (int i = 0; i < length; i++) {   
            int number = random.nextInt(randomStr.length());   
            strBuf.append(randomStr.charAt(number));   
        }   
        return strBuf.toString();   
     }

}
